package com.haois.mp.wechat.util;

import com.haois.mp.database.commom.CommonConstants;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * WxOAuth2AccessTokenUtil
 *
 */
@Component
public class WxOAuth2AccessTokenUtil {

	@Value("${server.session-timeout}")
	private int maxTime;

	private static final Logger logger = LoggerFactory
			.getLogger(WxOAuth2AccessTokenUtil.class);
	
	@Autowired
	private WxMpService wxMpService;

	private WxMpOAuth2AccessToken wxMpOAuth2AccessToken;

	// 获取WxMpOAuth2AccessToken
	public WxMpOAuth2AccessToken getWxMpOAuth2AccessToken(String code)
			throws WxErrorException {
		logger.debug("getWxMpOAuth2AccessToken.code:" + code );
		// 通过wxMpService获取
		wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
		return wxMpOAuth2AccessToken;
	}


	public void setWxMpOAuth2AccessToken(
			WxMpOAuth2AccessToken wxMpOAuth2AccessToken) {
		this.wxMpOAuth2AccessToken = wxMpOAuth2AccessToken;
	}

	// 获取WxMpOAuth2AccessToken的Openid
	public String getOpenid(String code, HttpServletRequest request) {
		request.getSession().setMaxInactiveInterval(maxTime);
		if (StringUtils.isNotEmpty(code)){
			try {
				logger.info("WX---Code:" + code);
				// 判断是否重复请求
				String sCode = (String)request.getSession().getAttribute("code");
				if(StringUtils.equals(sCode,code)){//二次提交
	        		logger.debug("code 二次提交");
	        		return this.getOpenid(request) ;
	        	}else{
	        		request.getSession().setAttribute("code", code);
	        	}
				// 判断是否重复请求 end
				String openid = getWxMpOAuth2AccessToken(code).getOpenId();
				request.getSession().setAttribute(CommonConstants.OPENID_KEY, openid);
				return openid;
			} catch (WxErrorException e) {
				logger.error("获取 openid 异常:{}", e);
				String openid = this.getOpenid(request);
				if(StringUtils.isNotEmpty(openid)){
					return openid;
				}
				logger.error("获取 openid 异常:{}=======================");
				return null;
			}
		}
		String openid = this.getOpenid(request);
		logger.info("openid -================-{}",openid);
		//重新保存session
		request.getSession().setAttribute(CommonConstants.OPENID_KEY, openid);
		return openid;
	}

	public String getOpenid(HttpServletRequest request) {
		return (String) request.getSession().getAttribute(
				CommonConstants.OPENID_KEY);
	}


	// 获取WxMpOAuth2AccessToken的AccessToken
	public String getAccessToken() {
		try {
			return wxMpService.getAccessToken();
		} catch (WxErrorException e) {
			logger.error("获取 access_token 异常:{}", e);
		}
		return null;
	}
}
